package com.yuexunit.mobilenurse.module.Patients.ui;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.android.joyree.JoyreeScannerInterface;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Login.ui.Act_Login;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.Act_PatientDetail_Joyree;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_PatientList_Joyree;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_Upload;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.utils.PreferenceHelper;

/**
 * Created by work-jx on 2017/6/14.
 */
public class Act_Main_Joyree extends KJActivity {
    @BindView(id = R.id.bottombar_content1, click = true)
    private RadioButton mRbtnContent1;
    @BindView(id = R.id.bottombar_content2, click = true)
    private RadioButton mRbtnContent2;
    @BindView(id = R.id.bottombar_content3, click = true)
    private RadioButton mRbtnContent3;

    private Frag_PatientList_Joyree contentFragment1;
    private Frag_Upload contentFragment2;
    private Frag_Upload contentFragment3;
    private KJFragment currentFragment;

//    private boolean isRegister = false;
    private IntentFilter mBarcodeFilter = null;

    public static final String BARCODE_DATA_ACTION = "android.intent.action.BARCODEDATA";
    public static final String BARCODE_RESULT = "barcode_result";

    public JoyreeScannerInterface mScanner = null;

    @Override
    public void initData() {
        super.initData();
        AppConfig.ISOVER_PATIENT=false;
        contentFragment1 = new Frag_PatientList_Joyree();
//        contentFragment2 = new Frag_Upload();
        contentFragment3 = new Frag_Upload();
    }

    @Override
    public void onResume(){
        super.onResume();

        mScanner = new JoyreeScannerInterface(getApplication());
        mScanner.enableBeep(true);
        mScanner.enableVibrate(true);
        mScanner.setOutputMode(0);

        mBarcodeFilter = new IntentFilter();
        mBarcodeFilter.addAction(BARCODE_DATA_ACTION);

//        if (!isRegister) {
            registerReceiver(mBarcodeReceiver, mBarcodeFilter);
//            isRegister = true;
//        }
    }

    @Override
    public void onStop(){
        super.onStop();
        try {
            unregisterReceiver(mBarcodeReceiver);
        } catch (IllegalArgumentException e) {

        }

        mScanner = null;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        try {
            unregisterReceiver(mBarcodeReceiver);
        } catch (IllegalArgumentException e) {

        }

        mScanner = null;
    }

    @Override
    public void initWidget() {
        super.initWidget();
        changeFragment(contentFragment1);
    }

    public void changeFragment(KJFragment targetFragment) {
        currentFragment = targetFragment;
        super.changeFragment(R.id.main_content, targetFragment);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.bottombar_content1:
                changeFragment(contentFragment1);
                break;
            case R.id.bottombar_content2:
                //changeFragment(contentFragment2);
                break;
            case R.id.bottombar_content3:
                changeFragment(contentFragment3);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_main);
    }

    private BroadcastReceiver mBarcodeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            if (intent != null && intent.getStringExtra(BARCODE_RESULT) != null) {
                String mBarcodeData = intent.getStringExtra(BARCODE_RESULT);
                if(!mBarcodeData.equals(""))
                {
                    if(AppConfig.ISOVER_PATIENT) {
                        if (mBarcodeData.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_WD_RULE))) {
                            if(contentFragment1.JudgeVisitNo(mBarcodeData)) {
                                PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO, mBarcodeData);
                                AppConfig.VISITNO = mBarcodeData;
                                showActivity(aty, Act_PatientDetail_Joyree.class);
                            }
                            else {
                                Toast.makeText(aty, "非本病区病人!", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(aty, "请扫描病人腕带!", Toast.LENGTH_LONG).show();
                        }
                    }
                    else{
                        Toast.makeText(aty, "病人列表尚未加载完!请加载完毕后,再扫描!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

    };

    public void onBackPressed() {
        dialog_exit();
    }

    private void dialog_exit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(aty);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("是否确认退出?"); //设置内容
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setClass(aty, Act_Login.class);
                aty.startActivity(intent);
                aty.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }
}
